package com.example.travel_front.Adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.travel_front.Model.DayDetail;
import com.example.travel_front.Model.Route;
import com.example.travel_front.R;

import java.util.List;

public class RoutesAdapter extends RecyclerView.Adapter<RoutesAdapter.MyViewHolder> {

    private List<Route> list;
    private OnItemClickListener onItemClickListener;

    public RoutesAdapter(List<Route> list) {
        this.list = list;
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_routes, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Route route = list.get(position);
        List<DayDetail> dayDetailList = route.dayDetailList;
        if (dayDetailList.isEmpty()) return;
        holder.dayNumberText.setText(
                position <= 9 ? "0" + (position + 1) : String.valueOf((position + 1))
        );
        String info = dayDetailList.get(0).location;
        if (dayDetailList.size() > 1) {
            info += " → " + dayDetailList.get(dayDetailList.size() - 1).location;
        }
        holder.cityInfoText.setText(info);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void loadData(List<Route> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView dayNumberText;
        TextView cityNameText;
        TextView cityInfoText;
        ImageView detailBtn;

        public MyViewHolder(View itemView) {
            super(itemView);

            dayNumberText = itemView.findViewById(R.id.dayNumber);
            cityNameText = itemView.findViewById(R.id.cityName);
            cityInfoText = itemView.findViewById(R.id.cityInfo);
            detailBtn = itemView.findViewById(R.id.bottomRightIcon);

            detailBtn.setOnClickListener((v) -> {
                int adapterPosition = getAdapterPosition();
                if (adapterPosition >= 0) {
                    onItemClickListener.onItemClick(list.get(adapterPosition), adapterPosition);
                }
            });
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(Route route, int position);
    }
}